package yz.cp.back.websocket.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import yz.cp.back.websocket.service.ITokenService;

/**
 * Created by xukangkang on 2019/3/18.
 */
@Slf4j
public class ChannelInInterceptor implements ChannelInterceptor {
    @Autowired
    private ITokenService tokenService;
    @Nullable
    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        log.warn("command {}",accessor.getCommand());
//        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
//            log.warn("stompCommand connect");
//            String token = accessor.getFirstNativeHeader("token");
//            log.warn("webSocket token is {}", token);
//            if (StringUtils.isNotEmpty(token)) {
//                SecUser secUser = tokenService.retrieveUser(token);
//                if(secUser!=null){
//                    Principal user =  new MyPrincipal(secUser.getId());
//                    accessor.setUser(user);
//                }
//
//            }
//        }
        return message;
    }

    @Override
    public void postSend(Message<?> message, MessageChannel channel, boolean sent) {

    }

    @Override
    public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, @Nullable Exception ex) {

    }

    @Override
    public boolean preReceive(MessageChannel channel) {
        return false;
    }

    @Nullable
    @Override
    public Message<?> postReceive(Message<?> message, MessageChannel channel) {
        return null;
    }

    @Override
    public void afterReceiveCompletion(@Nullable Message<?> message, MessageChannel channel, @Nullable Exception ex) {

    }
}
